import { FC, useEffect, useRef } from "react";
import classnames from "classnames";
import G6 from "@antv/g6";
import "./index.less";

interface IProps {
  data: AppAnalysisType;
  theme: ThemeType;
  width?: number;
  height?: number;
  onRender?: () => void;
}

function setInitialCollapsedState(
  node: any,
  depth = 0,
  indexId: string = "0",
  index: number = 0
) {
  if (depth > 0) {
    node.collapsed = true;
  }
  if (!node.id) {
    node.id = `${indexId}-${index}`;
  }
  if (node.children) {
    node.children.forEach((child: any, childIndex: number) => {
      setInitialCollapsedState(
        child,
        depth + 1,
        `${indexId}-${depth + 1}`,
        childIndex
      );
    });
  }
}

const AppAnalysis: FC<IProps> = (props) => {
  const { width, height, data, onRender, theme } = props;
  const wrapRef = useRef<HTMLDivElement | null>(null);
  const graphRef = useRef<any | null>(null);
  const renderRef = useRef<boolean>(false);
  const generateTree = (data: any) => {
    if (!wrapRef.current) return;
    if (!graphRef.current) return;
    const graph = graphRef.current;
    graph.data(data);
    graph.render();
    graph.fitView();
  };

  useEffect(() => {
    if (renderRef.current) return;
    if (!wrapRef.current) return;
    renderRef.current = true;
    const container = wrapRef.current;
    const gWidth = width || container.clientWidth || 375;
    const gHeight = height || container.clientHeight || 375;
    console.log("gWidth", gWidth, gHeight);
    graphRef.current = new G6.TreeGraph({
      container: container,
      width: gWidth,
      height: gHeight,
      fitView: true,
      renderer: "canvas",
      modes: {
        default: [
          {
            type: "collapse-expand",
            relayout: true,
            onChange: function onChange(item: any, collapsed: any) {
              const data = item.get("model");
              data.collapsed = collapsed;
              return true;
            },
          },
          "drag-canvas",
          "zoom-canvas",
        ],
      },
      defaultNode: {
        size: 10,
        anchorPoints: [
          [0, 0.5],
          [1, 0.5],
        ],
        style: {
          width: 40, // 设置节点宽度
        },
        labelCfg: {
          style: {
            fontSize: 10,
            width: 40, // 设置文本宽度，使其与节点宽度一致
            lineWrap: true, // 开启文本自动换行
          },
        },
      },
      defaultEdge: {
        type: "cubic-horizontal",
      },
      layout: {
        type: "dendrogram",
        direction: "LR", // H / V / LR / RL / TB / BT
        nodeSep: 30,
        rankSep: 100,
      },
    });
    graphRef.current.get("canvas").set("localRefresh", false);
    graphRef.current.node(function (node: any) {
      const position =
        node.depth === 0 ? "left" : node.depth % 2 === 1 ? "top" : "bottom";
      return {
        label: node.name + `${node.value ? "(" + node.value + ")" : ""}`,
        labelCfg: {
          position:
            node.children && node.children.length > 0 ? position : "right",
          style: {
            fill: theme === "dark" ? "#FFF" : "#000",
          },
        },
      };
    });
    // graphRef.current.on('node:click', (e: any) => {
    //   const model = e.item.getModel();
    //   model.collapsed = !model.collapsed;
    //   if (graphRef.current) {
    //     graphRef.current.updateItem(e.item, model);
    //     graphRef.current.layout()
    //     graphRef.current.refresh()
    //   };
    // });
  }, []);

  const handleResize = () => {
    const graph = graphRef.current;
    const container = wrapRef.current;
    if (!graph || graph.get("destroyed")) return;
    if (!container || !container.clientWidth || !container.clientHeight) return;
    graph.changeSize(container.clientWidth, container.clientHeight);
  };

  // useEffect(() => {
  //   const observer = new ResizeObserver(handleResize);
  //   if (wrapRef.current) {
  //     observer.observe(wrapRef.current);
  //   }
  //   return () => {
  //     if (wrapRef.current) {
  //       observer.unobserve(wrapRef.current);
  //     }
  //   };
  // }, []);

  useEffect(() => {
    setInitialCollapsedState(data);
    generateTree(data);
  }, [data]);

  return <div className={classnames("app-analysis")} ref={wrapRef}></div>;
};

export default AppAnalysis;
